<template>
  <j-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    switchFullscreen
    @ok="handleSubmit"
    @cancel="close"
    style="top:50px"
    cancelText="关闭"
  >
    <template slot="footer">
      <a-button @click="close">取消</a-button>
      <a-button type="primary" :loading="loading" @click="handleSubmit" v-if="!disableSubmit">确认</a-button>
    </template>
    <a-spin tip="Loading..." :spinning="loading">
      <a-row :gutter="10" style="background-color: #FFF;" v-if="visible">
        <a-col :md="12" :sm="24">
          <a-card :bordered="false">
            <a-form layout="inline" @keyup.enter.native="searchQuery">
              <a-row :gutter="24">
                <a-col :lg="9" :md="9" :sm="24">
                  <a-form-item :labelCol="labelCol"
                               :wrapperCol="wrapperCol" label="职位编号">
                    <a-input placeholder="请输入名称模糊查询" v-model="queryParam.positionCode"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :lg="9" :md="9" :sm="24">
                  <a-form-item :labelCol="labelCol"
                               :wrapperCol="wrapperCol" label="职位名称">
                    <a-input placeholder="请输入名称模糊查询" v-model="queryParam.positionName"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :lg="6" :md="6" :sm="24">
                  <a-button type="primary" @click="onSearch" icon="search" style="margin-top: 5px">查询</a-button>
                </a-col>

              </a-row>
            </a-form>
            <a-table
              ref="table"
              size="small"
              class="Table"
              bordered
              :scroll="{
                   x:'max-content'
              }"
              tableLayout="auto"
              rowKey="positionCode"
              :columns="positionsColumns"
              :dataSource="dataSource"
              :pagination="ipagination"
              :loading="loading"
              :customRow="onClickRow"
              :rowSelection="{selectedRowKeys: selectedRowKeys,onSelect: onSelect,onSelectAll:onSelectAll}"
              @change="handleTableChange"
            >
              <template slot="status" slot-scope="text">{{ text | isActiveStatus }}</template>
            </a-table>

          </a-card>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-card :bordered="false">
            <a-table
              ref="table"
              size="small"
              class="Table"
              bordered
              :scroll="{
                x:'max-content'
              }"
              tableLayout="auto"
              rowKey="positionCode"
              :columns="positionsDataColumns"
              :dataSource="model.posVos"
            >
              <template slot="action" slot-scope="text, record, index">
                <a @click="handleDelete(record,index)">删除</a>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </a-spin>
  </j-modal>
</template>

<script>
import { filterObj } from '@/utils/util'
import { getAction, httpAction, postAction } from '@/api/manage'
import JInput from '@/components/cn-form/JInput.vue'
import SelectPosition from '@/components/cn-components/select-position'
import { PageListMixin } from '@/mixins/PageListMixin'

export default {
  name: 'dealer-white-modal',
  components: { JInput, SelectPosition },
  props: ['modalWidth', 'multi', 'userIds'],
  data() {
    return {
      typeLoading: false,
      queryParam: {
        code: '',
        name: '',
      },
      custCode: '',
      positionsData: [],
      treeData: [],
      scrollTrigger: {},
      selectedRowKeys: [],
      selectUserRows: [],
      selectUserIds: [],
      title: '职位配置',
      selectedKeys: [],
      visible: false,
      form: this.$form.createForm(this),
      loading: false,
      expandedKeys: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 9 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 }
      },
      positionsColumns: [
        {
          title: '#',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '职位编号',
          align: 'center',
          dataIndex: 'positionCode'
        },
        {
          title: '职位名称',
          align: 'center',
          dataIndex: 'positionName'
        },

      ],
      positionsDataColumns: [
        {
          title: '#',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '职位编号',
          align: 'center',
          dataIndex: 'positionCode'
        },
        {
          title: '职位名称',
          align: 'center',
          dataIndex: 'positionName'
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'action',
          width: 80,
          ellipsis: true,
          scopedSlots: { customRender: 'action' },
        },
      ],
      model:{},
      reqCode: '',
      activeKey: '3',
      url: {
        list: window._CONFIG['domianURL'] + '/cnPositionController/getPageList',
        add: window._CONFIG['domianURL'] + '/role/cnBpmRole/saveBpmRolePositon'
      },
      record: null
    }
  },
  mixins: [PageListMixin],
  computed: {
    // 计算属性的 getter
    getType: function () {
      return this.multi == true ? 'checkbox' : 'radio'
    }
  },
  watch: {},
  created() {
    // 该方法触发屏幕自适应
    this.resetScreenSize()
  },
  methods: {

    /**
     * 删除已选中商品
     * @param record
     */
    handleDelete(record,index) {
      this.selectionRows.remove(record)
      this.selectedRowKeys.remove(record['positionCode'])
      this.model.posVos.splice(index,1)
    },

    // 触发屏幕自适应
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.scrollTrigger = { x: 800 }
      } else {
        this.scrollTrigger = {}
      }
    },
    onClickRow(record) {
      return {
        on: {
          click: () => {
            const keys = this.selectedRowKeys
            if (keys.indexOf(record.positionCode) == -1) {
              keys.push(record.positionCode)
              this.selectionRows.push(record)
              this.model.posVos.push(record)
            } else {
              keys.remove(record.positionCode)
              this.selectionRows.remove(record)
              this.model.posVos.splice(keys.indexOf(record.positionCode),1)
            }
            this.selectedRowKeys = keys
          }
        }
      }
    },
    showModal(record) {
      if(record.vos&&record.vos.length){
        record.posVos = record.vos.map(item=>Object.assign({},{
          positionCode:item.bpmPositionCode,
          positionName:item.bpmPositionName,
        }))
        this.selectionRows= record.vos.map(item=>Object.assign({},{
          positionCode:item.bpmPositionCode,
          positionName:item.bpmPositionName,
        }))
        this.selectedRowKeys=record.posVos.map(item=>item.positionCode)
      }else {
        record.posVos=[]
        this.selectionRows=[]
        this.selectedRowKeys=[]
      }
      this.model = record
      this.visible = true
    },
    /**
     * 获取查询参数
     * @returns {*}
     */
    getQueryParams() {
      let param = Object.assign({}, this.queryParam)
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      return filterObj(param)
    },
    searchReset(num) {
      let that = this
      if (num !== 0) {
        that.loadData(1)
      }
      that.selectedRowKeys = []
      that.selectionRows = []
    },
    close() {
      this.searchReset(0)
      this.visible = false
    },
    handleSubmit() {
      let that = this
      that.loading = true
      if(!this.model.posVos||!this.model.posVos.length){
        this.$message.error('请选择职位！')
        return
      }
      let formData = Object.assign({},this.model)
      formData.posVos = formData.posVos.map(item=>item.positionCode)
      httpAction(this.url.add, formData, 'post').then((res) => {
        if (res.success) {
          this.close()
          that.$emit('ok')
          that.searchReset(0)
          that.$message.success(res.message)
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        that.loading = false
      })
    },
    /**
     * 手动全选/取消全选分类
     * @param selected
     * @param selectedRows
     * @param changeRows
     */
    onSelectAll(selected, selectedRows, changeRows) {
      this.selectedRowKeys = selectedRows.map(row => row.positionCode)
      this.selectionRows = selectedRows
      let posVos = this.model.posVos||[]
      if (selected) {
        //todo 选中
        changeRows.map(row => {
          posVos.push(row)
        })
      } else {
        //todo 取消选中
        changeRows.map(row => {
          let item = posVos.find(v=>v.positionCode == row.positionCode)
          item&&posVos.remove(item)
        })
      }
      this.model.posVos = posVos
    },

    /**
     * 手动勾选/取消分类
     * @param record
     * @param selected
     * @param selectedRows
     * @param nativeEvent
     */
    onSelect(record, selected, selectedRows, nativeEvent) {
      this.selectedRowKeys = selectedRows.map(row => row.positionCode)
      this.selectionRows = selectedRows
      let posVos = this.model.posVos||[]
      if (selected) {
        //todo 选中
        posVos.push(record)
      } else {
        //todo 取消选中
        let item = posVos.find(v=>v.positionCode == record.positionCode)
        item&&posVos.remove(item)
        // posVos.remove(record)
      }
      this.model.posVos = posVos

    },
    onSearch() {
      this.loadData(1)
    },

    /**
     * 获取分类树
     * @returns {*}
     */
    queryDepartTree() {
      this.typeLoading = true
      return postAction(window._CONFIG['domianURL'] + '/goodsclassify/cnGoodsClassify/getProductTypeTree').then((res) => {
        if (res.success) {
          this.treeData = this.handleStruct(res.result)
          // 默认展开父节点
          this.expandedKeys = this.treeData.map(item => item.code)
        }

        this.typeLoading = false
      }).catch(e => {
        this.$message.warning(res.message)
        this.typeLoading = false
      })
    },

  }
}
</script>

<style scoped>
.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

#components-layout-demo-custom-trigger .trigger {
  font-size: 18px;
  line-height: 64px;
  padding: 0 24px;
  cursor: pointer;
  transition: color .3s;
}
</style>
